package com.firstappdemo.controller;

import com.firstappdemo.domain.User;
import com.firstappdemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/webFlux")
public class WebFluxUserController {

    private final UserRepository userRepository;

    @Autowired
    public WebFluxUserController(UserRepository userRepository) {
        super();
        this.userRepository = userRepository;
    }

    @PostMapping("/saveUser")
    public Mono<User> saveUser(@RequestParam String name) {
        User user = new User(name);
        return Mono.justOrEmpty(userRepository.save(user) ? user : null).switchIfEmpty(Mono.error(new NullPointerException()));
    }
}
